
import {Notification } from 'element-ui'
import { aiImportCourseProgress } from '@/api/AIImport'

const getRet = (response) => {
  const dataList = response.data || []
  if (dataList && dataList.length > 0) {
    dataList.forEach(item => {
      if (item.status === 2 && item.progress === 100) {
        Notification.success({
          message: `《${item.courseName}》导入成功`,
          duration: 0 // 设置为0，消息永不自动关闭
        })
      }
      if (item.status === 3) {
        Notification.error({
          message: `《${item.courseName}》导入失败，原因：${item.failureCause}`,
          duration: 0 // 设置为0，消息永不自动关闭
        })
      }
    })
  }
  return dataList
}
const aiImport = {
  state: {
    importList: [],
    courseIds: [],
    polling: null,
    shouldPoll: false
  },
  getters: {
    importList: state => state.importList,
    courseIds: state => state.courseIds,
    polling: state => state.polling,
    shouldPoll: state => state.shouldPoll
  },
  mutations: {
    // 保存在导入课程ID
    SET_COURSES(state, courseIds) {
      state.courseIds = courseIds
    },
    // 保存正在导入课程数组
    SET_IMPORT_LIST(state, importList) {
      state.importList = importList
    },
    // 停止轮询
    STOP_POLLING(state) {
      console.log('stop polling-------------')
      if (state.polling) {
        clearInterval(state.polling)
      }
      state.polling = null
      state.shouldPoll = false
    },
    // 轮询状态
    SET_SHOULD_POLL(state, polling) {
      state.shouldPoll = polling
    },
  },
  actions: {
    startPolling({ commit, state }) {
      aiImportCourseProgress().then(response => {
        const dataList = getRet(response)
        commit('SET_COURSES', dataList.map(item => {
          if (item.status == 1) {
            return item.courseId
          }
        }))
        commit('SET_IMPORT_LIST', dataList)
        const noImport = dataList.every(course => course.status === 0)
        // 判断是否所有课程的状态为3或4
        const allDone = dataList.every(course => course.status === 2 || course.status === 3)
        if (allDone || noImport) {
          commit('STOP_POLLING')
        } else {
          if(state.shouldPoll){
            return
          }
          commit('SET_SHOULD_POLL', true)
          // 启动轮询
          state.polling = setInterval(() => {
            aiImportCourseProgress().then(response => {
              const dataList = response.data || []
              if (dataList && dataList.length > 0) {
                dataList.forEach(item => {
                  if(item.status===2&&item.progress===100){
                    Notification.success({
                      message: `《${item.courseName}》导入成功`,
                      duration: 0, // 设置为0，消息永不自动关闭
                    });
                  }
                  if(item.status===3){
                    Notification.error({
                      message: `《${item.courseName}》导入失败，原因：${item.failureCause}`,
                      duration: 0, // 设置为0，消息永不自动关闭
                    });
                  }
                })
              }
              commit('SET_COURSES', dataList.map(item => {
                if (item.status == 1) {
                  return item.courseId
                }
              }))
              commit('SET_IMPORT_LIST', dataList)
              const noImport = dataList.every(course => course.status === 0)
              // 判断是否所有课程的状态为3或4
              const allDone = dataList.every(course => course.status === 2 || course.status === 3)
              if (allDone || noImport) {
                commit('STOP_POLLING')
              }

            }).catch(error => {
              console.error('Error fetching courses:', error)
              commit('STOP_POLLING') // 如果发生错误，停止轮询
            })
          }, 120000) // 每2分钟轮询一次，根据需要调整间隔时间
        }
      }).catch(error => {
        console.error('Error fetching courses:', error)
        commit('STOP_POLLING') // 如果发生错误，停止轮询
      })
    }
  }
}
export default aiImport
